package com.lib.ui.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.lib.app.ActivityUtils;
import com.lib.base.R;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.views.webview_x5.X5WebView;
import com.lib.observer.ObserverManager;
import com.lib.ui.fragment.kit.BaseFragment;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import androidx.fragment.app.FragmentTransaction;


public abstract class BaseWebFragment extends BaseFragment {

    private LinearLayout lin_web;
    private ProgressBar p_bar;
    private X5WebView webView;

    private FrameLayout.LayoutParams params;

    BaseWebFragment baseWebFragment;

    public String token = "";

    private Handler handler = new Handler();

    private Handler handlerBack = new Handler() {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
                case 1: {
                    if (webView != null) {
                        webView.goBack();
                    }

                }
                break;
            }
        }
    };

    private View root, viewBg;


    @Override
    protected void onCreateView(View view, Bundle savedInstanceState) {
        root = getRootView();

        lin_web = root.findViewById(R.id.lin_web);
        p_bar = root.findViewById(R.id.p_bar);
        webView = new X5WebView(getContext());

        viewBg = root.findViewById(R.id.viewbg);

        params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        webView.setLayoutParams(params);
        lin_web.addView(webView);
        setWebView();
        onCreateView(webView);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(true);

        webView.addJavascriptInterface(javaScriptFunction, "AndroidInterface");
        webView.setWebViewClient(client);

        webView.setFocusableInTouchMode(true);
        webView.setFocusable(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }


        baseWebFragment = this;
    }

    protected abstract void myOnPageStarted(WebView webView, String s, Bitmap bitmap);

    protected abstract void myShouldOverrideUrlLoading(WebView webView, String url);

    protected abstract void myOnPageFinished(WebView webView, String s);

    private WebViewClient client = new WebViewClient() {


        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
            super.onPageStarted(webView, s, bitmap);
            myOnPageStarted(webView, s, bitmap);

        }

        /**
         * 防止加载网页时调起系统浏览器
         */
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {

            LogUtil.e(url);

            //网页调用打电话时操作
            if (url.startsWith("tel:")) {

                startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            } else {
                webView.loadUrl(url);

                myShouldOverrideUrlLoading(webView, url);
            }

            return true;
        }


        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);

//            webView.loadUrl("javascript:hideheader()");
            myOnPageFinished(webView, url);

        }
    };


    protected abstract void onCreateView(WebView webView);

    protected abstract int getLayoutId();

//    protected abstract void onDismissFragment();

    /**
     * 开始加载Url
     */

    public void setWebView() {

        try {

            webView.setWebChromeClient(new WebChromeClient() {

                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    super.onProgressChanged(view, newProgress);

                    if (newProgress >= 100) {

                        p_bar.setProgress(100);

                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {

                                p_bar.setVisibility(View.GONE);
                                viewBg.setVisibility(View.GONE);

                            }
                        }, 250);//3秒后执行Runnable中的run方法
                    } else {
                        p_bar.setVisibility(View.VISIBLE);
                        p_bar.setProgress(newProgress);
                    }

                }

            });

            //处理WebView点击返回事件
            webView.setOnKeyListener(new View.OnKeyListener() {

                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
                        if (event.getAction() == KeyEvent.ACTION_DOWN) { //只处理一次
                            handlerBack.sendEmptyMessage(1);
                        }
                        return true;
                    }
                    return false;
                }

            });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroyView() {

        if (webView != null) {

            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = webView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webView);
            }

            webView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.clearView();
            webView.removeAllViews();
            webView.destroy();

        }
        super.onDestroyView();
    }

    //------------------------------------------------------------------------------------JS交互

    /**
     * JS交互接口
     */
    public interface JavaScriptFunction {

        //获取Token
        String appGetToken();

        //在AI作业辅导直播间，隐藏弹出的抽奖框
        void appHideLuckyDraw();

    }

    private JavaScriptFunction javaScriptFunction = new JavaScriptFunction() {

        @JavascriptInterface
        public String appGetToken() {
            return token;
        }

        @JavascriptInterface
        public void appHideLuckyDraw() {

            LogUtil.e("H5已结束抽奖操作，需要关闭抽奖页弹出框！");
//            webView.goBack();

            //如果当前在AI作业辅导间，点击则销毁弹出框
            if (ActivityUtils.isForeground(getActivity(), "com.module_live.activity.CoachStudyLivingActivity")) {

                LogUtil.e("当前在AI作业辅导间");

//                FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
//                transaction.remove(baseWebFragment).commit();

                ObserverManager.getInstance().notifyObserver("closeLuckyDraw");

            } else {

                LogUtil.e("当前不在AI作业辅导间");
                onDestroyView();
            }

        }
    };

    @Override
    public void onResume() {
        super.onResume();

        token = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken();
    }
}
